<template>
  <div>
    <div class="table-title">
      <h3>学院信息表</h3>
    </div>
    <div class="user-show">
      <div class="user-table">
        <div class="user-table-utils">
          <div>
            <el-input placeholder="请输入查询内容" v-model="searchContent" class="input-with-select">
              <el-select v-model="searchItem" slot="prepend" placeholder="请选择查询项">
                <el-option v-for="item in searchItems" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
            </el-input>
          </div>
          <div>
            <el-button type="success" plain icon="el-icon-plus" @click="addUser">新增数据</el-button>
          </div>
        </div>
        <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="id" label="学院号">
          </el-table-column>
          <el-table-column prop="name" label="学院">
          </el-table-column>
          <el-table-column v-if="userRole" fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="margin-right: 10px;"
                @click="handleEdit(scope.row)">编辑</el-button>

              <el-popconfirm title="确定删除吗？" @confirm="handleDel(scope.row)">
                <el-button :loading="delLoading" slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <div class="user-pagination">
          <el-pagination background small layout="prev, pager, next" :total="pagination.total"
            :page-size="pagination.pageSize" :current-page="pagination.current" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

        <el-form-item label="学院名" prop="name">
          <el-input type="text" v-model="ruleForm.name" autocomplete="off" clearable />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleExit">取 消</el-button>
        <el-button type="success" plain  @click="handleSubmit" :loading="editLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import apis from '@/utils/api';
import request from '@/utils/requestMethod';
import './style.less';
import ifAdmin from '@/utils/judgeAdmin';
import { Message } from 'element-ui';

export default {
  name: 'collegeInfo',
  mounted() {
    this.fetchColleges();
    this.userRole = ifAdmin();
  },
  data() {
    /**
 *  对姓名进行校验
 */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入姓名'));
      } else if (value.length > 20) {
        callback(new Error('姓名不能超过20位'));
      } else {
        callback();
      }
    };

    return {
      dialogVisible: false,
      tableLoading: false,
      delLoading: false,
      editLoading: false,
      tableData: [],
      userRole: false,
      searchItem: '',
      dialogTitle: '新增学院',
      searchItems: [
        {
          label: '全部',
          value: 'all'
        },
        {
          label: '姓名',
          value: 'name'
        }
      ],
      searchContent: '',
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      editRow: {},
      ifSave: true,
      ruleForm: {
        name: '',
        workId: '',
        username: '',
        college: '',
        post: ''
      },
      ifSearch: false,
      rules: {
        name: [
          { validator: validateName, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     *  获取所有学院信息
     */
    fetchColleges() {
      this.tableLoading = true;
      const {
        pagination: {
          current,
          pageSize
        }
      } = this;

      request(apis.fetchCollegeInfo + `?current=${current}&pageSize=${pageSize}`).then(res => {
        const {
          objects,
          total
        } = res.data;
        this.pagination.total = total;

        this.tableData = objects;
      }).finally(() => {
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false;
      });
    },

    /**
     *  点击新增按钮事件
     */
    addUser() {
      this.ifSave = true;
      this.dialogVisible = true;
      this.dialogTitle = '新增学院';
      this.ruleForm = {
        name: '',
        id: ''
      };
    },

    /**
     * 点击编辑按钮事件
     */
    handleEdit(row) {
      this.ifSave = false;
      this.dialogVisible = true;
      this.editRow = row;
      this.ruleForm = row;
      this.dialogTitle = '修改学院信息'
    },

    /**
     * 点击取消按钮事件
     */
    handleExit() {
      this.dialogVisible = false;
      this.editLoading = false;
    },

    /**
     *  处理表格编辑与新增事件
     */
    handleSubmit() {
      this.$refs['ruleForm'].validate((valid) => {
        const {
          ruleForm,
          editRow,
          ifSave
        } = this;

        if (valid) {
          this.editLoading = true;

          for (const item in ruleForm) {
            editRow[item] = ruleForm[item];
          }

          request(apis.editOrSaveCollege, {
            method: 'POST',
            body: ifSave ? ruleForm : editRow
          }).then(res => {
            const {
              objects,
              message
            } = res.data;
            if (objects) {
              Message.success(message);
              this.dialogVisible = false;
            } else {
              const errMessage = ifSave ? '新增学院失败' : '修改学院失败';
              Message.warning(errMessage);
            }
          }).finally(() => {
            this.fetchColleges();
            this.editLoading = false;
          }).catch(() => {
            this.editLoading = false;
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },

    /**
     * 处理表格删除事件
     */
    handleDel(row) {
      this.delLoading = true;
      request(apis.delCollege, {
        method: 'POST',
        body: row
      }).then(res => {
        const {
          objects,
          message
        } = res.data;
        if (objects) {
          Message.success(message);
        }
      }).finally(() => {
        this.delLoading = false;
        this.fetchColleges();
      }).catch(() => {
        Message.error("删除失败");
        this.delLoading = false;
      })
    },

    /**
     * 处理翻页事件
     */
    handleCurrentChange(value) {
      this.pagination.current = value;
      if (this.ifSearch) {
        this.handleSearch();
      } else {
        this.fetchColleges();
      }
    },
    handleClose(done) {
      done();
    },

    /**
     *  处理搜索事件
     */
    handleSearch() {
      this.ifSearch = true;
      const {
        searchItem,
        searchContent,
        pagination: {
          current,
          pageSize
        }
      } = this;

      if (searchItem === 'all') {
        this.fetchColleges();
        this.searchContent = '';
        this.searchItem = '';
        this.ifSearch = false;
      } else {
        if (searchItem === '') {
          Message.warning('请输入搜索项');
        }
        if (searchContent === '') {
          Message.warning('请输入搜索内容');
        }
      }

      if (searchContent !== '' && searchItem !== '' && searchItem !== 'all') {
        const content = searchContent;
        const body = {
          searchItem,
          content,
          current,
          pageSize
        }
        this.tableLoading = true;
        request(apis.searchColleges, {
          method: 'POST',
          body
        }).then(res => {
          const {
            objects,
            message,
            total
          } = res.data;

          this.pagination.total = total;
          this.tableData = objects;
          Message.success(message);

        }).finally(() => {
          this.tableLoading = false;
        }).catch(() => {
          this.tableLoading = false;
          Message.error('搜索失败');
        })
      }
    }
  }
}
</script>